package cch._2;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.*;


public class _2LoginServlet extends HttpServlet {
    Connection dbconn = null;
    public void init() {

        String dburl  = "jdbc:mysql://localhost:3306/cc?useSSL=false&serverTimezone=UTC";
        String username ="root";
        String password = "root";
        try{
            Class.forName("com.mysql.cj.jdbc.Driver");
            dbconn = DriverManager.getConnection(dburl,username,password);
            System.out.println("数据库连接成功");
        }catch (ClassNotFoundException e1){
            System.out.println(e1+"驱动程序找不到");
        }catch(SQLException e2){
            System.out.println(e2);
        }
    }
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        request.getRequestDispatcher("/login2.jsp").forward(request,response);

    }
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=utf-8");

        String name = request.getParameter("name");
        String pw = request.getParameter("password");


        try{
            String sql = "select * from user where name=?";
            PreparedStatement pstmt = dbconn.prepareStatement(sql);
            pstmt.setString(1,name);
            ResultSet result = pstmt.executeQuery();
            if(result.next()){
                if (result.getString("password").equals(pw)){
                    User user=new User();
                    user.setName(result.getString("name"));
                    user.setPassword(result.getString("password"));
                    request.getSession().setAttribute("user",user.getName());
                    System.out.println("cc1"+request.getSession().getAttribute("user"));
                    System.out.println("登陆成功");
                    response.sendRedirect("loginSuccess.jsp");
                }else{
                    System.out.println("登陆失败");
                    request.getSession().removeAttribute("user");
                    response.sendRedirect("loginFail.jsp");
                }


            }else{
                System.out.println("用户名不存在");
            }
        }catch(SQLException e){
            e.printStackTrace();
        }



    }
    public void destroy(){
        try{
            dbconn.close();
        }catch(Exception e){
            e.printStackTrace();
        }
    }
}